package com.doroodo.base.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.doroodo.base.fixflow.FixFlowMag;
import com.doroodo.base.fixflow.service.FlowCenterService;
import com.doroodo.base.fixflow.service.JobService;
import com.doroodo.base.fixflow.service.ProcessDefinitionService;
import com.doroodo.base.fixflow.service.ProcessInstanceService;
import com.doroodo.base.fixflow.service.TaskInstanceService;
import com.doroodo.base.fixflow.service.UserGroupService;
import com.doroodo.base.util.excelTools.ExcelUtils;
import com.doroodo.base.util.excelTools.JsGridReportBase;
import com.doroodo.base.util.excelTools.TableData;
import com.doroodo.sys.model.SyFile;
import com.doroodo.sys.service.SyFileService;
import com.doroodo.util.SmarteUntil;
import com.founder.fix.fixflow.core.ModelService;
import com.founder.fix.fixflow.core.ProcessEngine;
import com.founder.fix.fixflow.core.impl.command.StartProcessInstanceCommand;
import com.founder.fix.fixflow.core.runtime.ProcessInstance;
import com.founder.fix.fixflow.util.SpringConfigLoadHelper;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport {
	public static final String GET_ER = "获取数据失败!";
	public static final String ADD_SUC = "新增成功!";
	public static final String EDIT_SUC = "修改成功!";
	public static final String ADD_ER = "新增失败!";
	public static final String EDIT_ER = "修改失败!";
	public static final String SET_SUC = "设置成功!";
	public static final String SET_ER = "设置失败!";
	public static final String DEL_SUC = "删除成功!";
	public static final String DEL_ER_MAIN = "该数据正在被使用!";
	public static final String LOGIN_YES = "认证成功!";
	public static final String LOGIN_NO = "请您输入认证信息!";
	public static final String LOGIN_ER = "用户名或密码错误，请重新填写!";
	public static final String OPT_ERROR = "<div style=\"color:red;width: 100%;height: 20px;text-align:center;margin: 0px auto;margin-bottom:20px;\"><h1>您没有权限，请管理员授权!</h1></div>";
	public static final String OPT_DLG_ERROR = "<div style=\"color:red;width: 100%;height: 20px;text-align:center;margin: 0px auto;margin-bottom:20px;\">您没有权限，请管理员授权!</div>";
	public static final String FIle_UPLOAD_SUC = "上传成功!";
	public static final String FIle_UPLOAD_ER = "上传失败!";
	public static final String READHASE = "已存在,请重新填写!";
	public static final String STARTWORKFOW_SUC = "启动流程成功!";
	public static final String STARTWORKFOW_ER = "启动流程失败，请联系管理员，流程编号";
	public static final String DOWORKFOW_SUC = "您成功完成该任务!";
	public static final String DOWORKFOW_ER = "您执行该任务失败!";
	public static final String NOFILE = "请选择文件!";
	public static final String UPFILE_SUC = "文件上传成功!";
	public static final String UPFILE_ER = "文件上传失败!";
	public static final String UPDATA_SUC = "数据导入成功!";
	public static final String UPDATA_ER = "数据导入失败!请仔细阅读帮助，并确保数据文件格式正确!";
	public static SmarteUntil SUNTIL;
	
	@Autowired
	private FixFlowMag fixFlowMag;
	@Autowired
	public SyFileService syFileService;
	private SyFile syFile;
	private List<File> fileGroup;
	private String fileid;
	private String excelExportAll = "false";// 页面导出，true导出全部数据，false导出当前页数据

	public String getExcelExportAll() {
		return excelExportAll;
	}

	public void setExcelExportAll(String excelExportAll) {
		this.excelExportAll = excelExportAll;
	}

	public String getFileid() {
		return fileid;
	}

	public void setFileid(String fileid) {
		this.fileid = fileid;
	}

	private List<String> fileGroupFileName;

	public List<String> getFileGroupFileName() {
		return fileGroupFileName;
	}

	public void setFileGroupFileName(List<String> fileGroupFileName) {
		this.fileGroupFileName = fileGroupFileName;
	}

	public List<String> getFileGroupContentType() {
		return fileGroupContentType;
	}

	public void setFileGroupContentType(List<String> fileGroupContentType) {
		this.fileGroupContentType = fileGroupContentType;
	}

	private List<String> fileGroupContentType;

	public SyFile getSyFile() {
		return syFile;
	}

	public List<File> getFileGroup() {
		return fileGroup;
	}

	public void setFileGroup(List<File> fileGroup) {
		this.fileGroup = fileGroup;
	}

	public void setSyFile(SyFile syFile) {
		this.syFile = syFile;
	}

	private int page = 0;
	private int rows = 0;
	private String searchKey = "";
	private String searchName = "";
	private String id = "";
	protected String ids = "";
	private String hearders = "";
	private String fields = "";
	private File uploadFile; // 上传的文件
	private String uploadFileFileName; // 文件名称
	private String uploadFileContentType; // 文件类型

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getUploadFileFileName() {
		return uploadFileFileName;
	}

	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}

	public String getUploadFileContentType() {
		return uploadFileContentType;
	}

	public void setUploadFileContentType(String uploadFileContentType) {
		this.uploadFileContentType = uploadFileContentType;
	}

	public String getHearders() {
		return hearders;
	}

	public void setHearders(String hearders) {
		this.hearders = hearders;
	}

	public String getFields() {
		return fields;
	}

	public void setFields(String fields) {
		this.fields = fields;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getSearchKey() {
		return searchKey;
	}

	public void setSearchKey(String searchKey) {
		this.searchKey = searchKey;
	}

	public String getSearchName() {
		return searchName;
	}

	public void setSearchName(String searchName) {
		this.searchName = searchName;
	}

	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	public Map<String, Object> getSession() {
		return ActionContext.getContext().getSession();
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	// 流程相关
	private String processDefinitionId = "";
	private String processDefinitionKey = "";
	private String taskId = "";
	private String processInstanceId = "";
	private String commandType = "";
	private String commandId = "";
	private String businessKey = "";
	private String taskComment = "";
	private String taskParams = "";

	public String getTaskParams() {
		return taskParams;
	}

	public void setTaskParams(String taskParams) {
		this.taskParams = taskParams;
	}

	public String getCommandType() {
		return commandType;
	}

	public void setCommandType(String commandType) {
		this.commandType = commandType;
	}

	public String getCommandId() {
		return commandId;
	}

	public void setCommandId(String commandId) {
		this.commandId = commandId;
	}

	public String getBusinessKey() {
		return businessKey;
	}

	public void setBusinessKey(String businessKey) {
		this.businessKey = businessKey;
	}

	public String getTaskComment() {
		return taskComment;
	}

	public void setTaskComment(String taskComment) {
		this.taskComment = taskComment;
	}

	public String getProcessInstanceId() {
		return processInstanceId;
	}

	public void setProcessInstanceId(String processInstanceId) {
		this.processInstanceId = processInstanceId;
	}

	public String getTaskId() {
		return taskId;
	}

	public void setTaskId(String taskId) {
		this.taskId = taskId;
	}

	public String getProcessDefinitionKey() {
		return processDefinitionKey;
	}

	public void setProcessDefinitionKey(String processDefinitionKey) {
		this.processDefinitionKey = processDefinitionKey;
	}

	public String getProcessDefinitionId() {
		return processDefinitionId;
	}

	public void setProcessDefinitionId(String processDefinitionId) {
		this.processDefinitionId = processDefinitionId;
	}

	public ProcessInstanceService getFlowManager() {
		return (ProcessInstanceService) SpringConfigLoadHelper
				.getBean("processInstanceServiceImpl");
	}

	public TaskInstanceService getTaskManager() {
		return (TaskInstanceService) SpringConfigLoadHelper
				.getBean("taskInstanceServiceImpl");
	}

	public ProcessDefinitionService getProcessDefinitionService() {
		return (ProcessDefinitionService) SpringConfigLoadHelper
				.getBean("processDefinitionServiceImpl");
	}

	public UserGroupService getUserGroupService() {
		return (UserGroupService) SpringConfigLoadHelper
				.getBean("userGroupServiceImpl");
	}

	public JobService getJobService() {
		return (JobService) SpringConfigLoadHelper.getBean("jobServiceImpl");
	}

	public FlowCenterService getFlowCenter() {
		return (FlowCenterService) SpringConfigLoadHelper
				.getBean("flowCenterServiceImpl");
	}

	protected Map<String, Object> getFlowToolBarBytaskId(
			Map<String, Object> filter) {
		Map<String, Object> result = null;
		Map<String, Object> map = new HashMap();
		try {
			result = this.getFlowCenter().GetFlowRefInfo(filter);
			map.put("commandList", result.get("commandList"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return map;
	}

	protected Map<String, Object> getTaskDetailInfo(Map<String, Object> filter) {
		Map<String, Object> result = null;
		try {
			result = this.getFlowCenter().getTaskDetailInfo(filter);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	public void writeText(String str) {
		try {
			getResponse().setContentType("text/html;charset=utf-8");
			getResponse().getWriter().write(str);
			getResponse().getWriter().flush();
			getResponse().getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void writeJson(Object object) {
		try {
			String json = JSON.toJSONStringWithDateFormat(object,"yyyy-MM-dd HH:mm:ss");
			getResponse().setContentType("text/html;charset=utf-8");
			getResponse().getWriter().write(json);
			getResponse().getWriter().flush();
			getResponse().getWriter().close();
			// System.out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void writeMsg(String msg) {
		Map map = new HashMap<String, String>();
		map.put("info", msg);
		this.writeJson(map);
	}

	public String getLoginUserName() {
		return (String) this.getSession().get("username");
	}

	public String getLoginUserId() {
		return (String) this.getSession().get("userid");
	}

	public String getLoginUserRole() {
		return (String) this.getSession().get("userrole");
	}

	public void isLogin() {
		String user = getLoginUserName();
		Map<String, Comparable> map = new HashMap();
		if (user != null) {
			map.put("info", LOGIN_YES);
			map.put("islogin", 1);
		} else {
			map.put("info", LOGIN_NO);
			map.put("islogin", 0);
		}
		this.writeJson(map);
	}

	public void isErr() {
		this.writeText(OPT_ERROR);
	}

	public  void excel(String title, List<Object> list) {
		if (list == null)return;
		this.getResponse().setContentType("application/msexcel;charset=GBK");
		String[] hearders = null;
		String hearderString = "";
		try {
			hearderString = URLDecoder.decode(this.getHearders(), "utf-8");
			hearders = hearderString.split(",");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}// 表头数组
		String[] fields = this.getFields().split(",");
		TableData td = ExcelUtils.createTableData(list,
				ExcelUtils.createTableHeader(hearders), fields);
		try {
			JsGridReportBase report = new JsGridReportBase(this.getRequest(),
					this.getResponse());
			String user = (String) this.getSession().get("username");
			report.exportToExcel(title, user, td);
		} catch (Exception e) {
			e.toString();
		}
	}

	public void fileUpload(String uploadDir) throws IOException {
		String realpath = ServletActionContext.getServletContext().getRealPath(
				"/" + uploadDir);
		if (uploadFile != null) {
			File savefile = new File(new File(realpath), uploadFileFileName);
			if (!savefile.getParentFile().exists())
				savefile.getParentFile().mkdirs();
			FileUtils.copyFile(uploadFile, savefile);
			this.writeMsg(FIle_UPLOAD_SUC);
		} else {
			this.writeMsg(FIle_UPLOAD_ER);
		}
	}


	// 获取流程图片
	protected InputStream getFlowImageByDefId(String defId) {
		ProcessEngine processEngine = fixFlowMag.getProcessEngine();
		;
		ModelService modelService = processEngine.getModelService();
		InputStream streamById = null;
		try {
			streamById = modelService.GetFlowGraphicsImgStreamByDefId(defId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return streamById;
	}

	// 启动流程
	protected ProcessInstance startOneProc(String processDefinitionKey,
			String businessKey, String authorId) {
		ProcessEngine processEngine = fixFlowMag.getProcessEngine();
		;
		// 创建一个启动命令
		StartProcessInstanceCommand startProcessInstanceCommand = new StartProcessInstanceCommand();
		// 设置需要启动的流程的KEY
		startProcessInstanceCommand
				.setProcessDefinitionKey(processDefinitionKey);
		// 设置业务关联键
		startProcessInstanceCommand.setBusinessKey(businessKey);
		// 设置流程的启动人
		startProcessInstanceCommand.setStartAuthor(authorId);
		// 启动流程，返回流程实例
		return processEngine.getRuntimeService().noneStartProcessInstance(
				startProcessInstanceCommand);
	}

	public Map<String, String> uploadFiles(List<File> fileGroup,
			List<String> fileGroupFileName, String dirs) throws Exception {
		// 获取文件存储路径
		String path = ServletActionContext.getRequest().getRealPath("/fileupload/");
		Map map = new HashMap<String, String>();
		if (!dirs.isEmpty())
			(new File(path + dirs)).mkdirs();
		for (int i = 0; i < fileGroup.size(); i++) {
			String sysFileNameString = dirs
					+ (new SimpleDateFormat("yyyyMMddHHmmssSSS")
							.format(new Date()));
			sysFileNameString += fileGroupFileName.get(i).substring(
					fileGroupFileName.get(i).lastIndexOf("."));
			OutputStream os = new FileOutputStream(new File(path,
					sysFileNameString));
			map.put(fileGroupFileName.get(i), sysFileNameString);
			InputStream is = new FileInputStream(fileGroup.get(i));
			byte[] buf = new byte[1024];
			int length = 0;
			while (-1 != (length = is.read(buf))) {
				os.write(buf, 0, length);
			}
			is.close();
			os.close();
		}
		return map;
	}
}
